// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')
const dayjs = require('dayjs')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async event => {
  const { type, override, dateRange, screenIds, resourceIds } = event
  if (
    !type ||
    override === undefined ||
    !dateRange ||
    !screenIds ||
    !resourceIds
  ) {
    throw new Error('missing parameters')
  }
  if (dateRange[1] < dateRange[0]) {
    throw new Error('invalid date range')
  }
  const collection = `${type}-cast`

  const { data: resources } = await db
    .collection(type)
    .where({ _id: _.in(resourceIds) })
    .orderBy('createAt', 'asc')
    .get()

  if (override) {
    await db
      .collection(collection)
      .where({
        screenId: _.in(screenIds),
        date: _.and(_.gte(dateRange[0]), _.lte(dateRange[1])),
      })
      .remove()
  }

  const data = []
  for (let screenId of screenIds) {
    for (
      let date = dateRange[0];
      date <= dateRange[1];
      date = dayjs(date).add(1, 'day').format('YYYY-MM-DD')
    ) {
      data.push({ screenId, date, resources })
    }
  }
  await db.collection(collection).add({ data })

  const { data: sData } = await db
    .collection('screen')
    .where({ _id: _.in(screenIds) })
    .get()

  const promises = sData.map(v =>
    axios.get('http://124.70.50.10:33333/sendMsg', {
      params: { sn: v.sn, msg: type === 'image' ? 'cast' : 'vidoe' },
    })
  )
  await Promise.all(promises)
}
